using System.Collections.ObjectModel;
using System.Drawing;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using black_screen_client.Models;
using Hardcodet.Wpf.TaskbarNotification;

namespace black_screen_client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        bool isServerOk = false;
        private readonly object statusLockObject = new object(); // 用于状态更新的锁对象
        bool isRegister = false;
        public static MainWindow? Instance;
        TcpClientHelper tcpClient = new TcpClientHelper();
        GroupResponseData groupInfo = new GroupResponseData();
        int groupId = -1;
        BlackScreenStartData blackScreenStartData = new BlackScreenStartData();
        BlackScreenEndData blackScreenEndData = new BlackScreenEndData();
        LogResponseData logResponseData = new LogResponseData();
        RencentEvents rencentEvents =null;
        public Screen screen = null;
        Thread heardThread = null;
        DateTime heartTime = DateTime.Now;
        DateTime responseHeartTime = DateTime.Now;

        System.Windows.Threading.DispatcherTimer heartTimer = null;

        ReaderWriterLockSlim mutex = new ReaderWriterLockSlim();

        MainControl mcControl;

        //黑屏示例初始化
      //  Screen screen = new Screen(new SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 0, 0)), new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255)));

        public MainWindow(MainControl mainControl)
        {
            InitializeComponent();
            Instance = this;
            this.screen = new Screen(btnBackgroundColor.Background, btnTextColor.Background);
            mcControl = mainControl;
        }


        public void DataReceived(byte[] buffer, int length)
        {
            string msg = Encoding.UTF8.GetString(buffer, 0, length);
            DataPacket dataPacket = Newtonsoft.Json.JsonConvert.DeserializeObject<DataPacket>(msg);
            if (dataPacket.PacketType == (int)DataPacketType.GroupResponse)
            {
                // 立即处理分组响应数据
                GroupResponseData tempGroupInfo = new GroupResponseData();
                tempGroupInfo.JsonToPacket(dataPacket.PacketData);
                
                // 更新全局分组信息
                this.groupInfo = tempGroupInfo;
                
                Logger.Singleton.Info($"收到分组数据，共{tempGroupInfo.GroupInfos.Count}个分组");
                
                // 使用Invoke确保在UI线程上立即执行，而不是BeginInvoke延迟执行
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    try
                    {
                        // 清空并重新添加所有分组
                        cmbChooseGroup.Items.Clear();
                        
                        if (tempGroupInfo.GroupInfos.Count > 0)
                        {
                            foreach (var item in tempGroupInfo.GroupInfos)
                            {
                                cmbChooseGroup.Items.Add(item.Name);
                            }
                            
                            // 自动选择第一个分组
                            cmbChooseGroup.SelectedIndex = 0;
                            Logger.Singleton.Info($"分组下拉框已更新，自动选择第一个分组: {cmbChooseGroup.SelectedItem}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Singleton.Error("更新分组下拉框时出错: " + ex.Message, ex);
                    }
                });

            }
            if (dataPacket.PacketType == (int)DataPacketType.BlackScreenStart)
            {
                // do something
                blackScreenStartData.JsonToPacket(dataPacket.PacketData);
                DateTime black_begin =  Convert.ToDateTime(blackScreenStartData.BeginTime);
                Logger.Singleton.Info($"收到黑屏开始指令----黑屏开始时间：{blackScreenStartData.BeginTime}");

                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.btnBlackScreen.IsEnabled = true;
                    screen.isBlackScreen = true;
                    screen.groupName = cmbChooseGroup.SelectedItem.ToString();
                   // screen.LogRequest += Screen_LogRequest;
                    screen.dt = black_begin;
                    //if(cmbChooseGroup.SelectedItem != null)
                    // screen.txtGroupName.Text = cmbChooseGroup.SelectedItem.ToString().Trim()+"单元已进入黑屏状态";
                    screen.groupId = this.groupId;
                    ProjectTools.ShowWindow(screen, Utils.ScreenPosition.Center);
                    screen.Visibility = Visibility.Visible;
                    this.Visibility = Visibility.Collapsed;
                    ApplyOpacityFromTextBox();
                    screen.CompositionTarget_Rendering(null, EventArgs.Empty);

                }));
            }
            if(dataPacket.PacketType == (int) DataPacketType.BlackScreenEnd)
            {
                   // do something
                blackScreenEndData.JsonToPacket(dataPacket.PacketData);
                //Zekun TODO: 关闭黑屏
                Logger.Singleton.Info($"收到黑屏结束指令----黑屏结束时间：{DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss")}");
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.btnBlackScreen.IsEnabled = false;
                    if(screen != null)
                    {
                        screen.isBlackScreen = false;
                        screen.Visibility = Visibility.Collapsed;
                        ProjectTools.ShowWindow(this, Utils.ScreenPosition.Center);
                       // this.Visibility = Visibility.Visible;
                    }
                }));
            }

            if(dataPacket.PacketType == (int) DataPacketType.LogResponse)
            {
                // do something
                logResponseData.JsonToPacket(dataPacket.PacketData);
                //Zekun TODO: 日志信息               
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (rencentEvents != null)
                    {
                        rencentEvents.Close();
                        rencentEvents = new RencentEvents();
                    }
                    else
                        rencentEvents = new RencentEvents();
                    //Logger.Singleton.Info("收到日志事件响应，打开日志事件记录！");
                    rencentEvents.LoadReport(logResponseData.PacketToJson());
                    ProjectTools.ShowWindow(rencentEvents, Utils.ScreenPosition.Center);
                    //rencentEvents.Show();
                }));


               
            }

            if(dataPacket.PacketType == (int) DataPacketType.HeartResponse)
            {
                // do something
                HeartResponseData heartResponseData = new HeartResponseData();
                heartResponseData.JsonToPacket(dataPacket.PacketData);
                //心跳响应
                if(heartResponseData.clientId == ProjectTools.getTcpServer().ClientId)
                {
                    System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        this.setHeartTime(DateTime.Now);
                    }));
                }
            }
         
        }

      

        private void Screen_LogRequest(int groupId)
        {
            this.LogRequest(groupId);
        }

        private DateTime getHeartTime()
        {
            DateTime dt = DateTime.Now;
            mutex.EnterReadLock();
            dt = heartTime;
            mutex.ExitReadLock();
            return dt;
        }

        private void setHeartTime(DateTime time)
        {
            mutex.EnterWriteLock();
            heartTime = time;
            mutex.ExitWriteLock();
        }

        private void heartThreadFun()
        {
            while (true)
            {
                DateTime dt = getHeartTime();
                if((DateTime.Now - dt).TotalSeconds > 18)
                {
                    //服务器掉线
                    if(screen != null)
                    {
                        SetServerStatus(false);
                        Logger.Singleton.Error("客户端与服务端连接掉线！");
                        break;
                    }    
                }
                if (getServerStatus() && (DateTime.Now- dt).TotalSeconds >15)
                {
                    HeartRequestData heartRequestData = new HeartRequestData();
                    heartRequestData.clientId = ProjectTools.getTcpServer().ClientId;
                    DataPacket dataPacket = new DataPacket((int)DataPacketType.HeartRequest, heartRequestData.PacketToJson());
                    var msg = Newtonsoft.Json.JsonConvert.SerializeObject(dataPacket);
                    //string转buffer
                    byte[] buffer = Encoding.UTF8.GetBytes(msg);
                    tcpClient.sendMessage(buffer);
                }
            }
        }

        //手动弹出黑屏
        private void btnBlackScreen_Click(object sender, RoutedEventArgs e)
        {
            Screen screen = new Screen(btnBackgroundColor.Background, btnTextColor.Background);
            screen.setPreview(true);
            ProjectTools.ShowWindow(screen, Utils.ScreenPosition.Center);
            //screen.Show();
            this.Close();
            ApplyOpacityFromTextBox();
        }

        //背景颜色盘
        private void btnBackgroundColor_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();

            if (colorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.Windows.Media.Color color = System.Windows.Media.Color.FromArgb(colorDialog.Color.A, colorDialog.Color.R, colorDialog.Color.G, colorDialog.Color.B);

                txtBackgourndColor.Text = "#" + color.ToString().Substring(3);

                SolidColorBrush brush = new SolidColorBrush(color);
                btnBackgroundColor.Background = brush;
            }
        }

        //文字颜色盘
        private void btnTextColor_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();

            if (colorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.Windows.Media.Color color = System.Windows.Media.Color.FromArgb(colorDialog.Color.A, colorDialog.Color.R, colorDialog.Color.G, colorDialog.Color.B);

                txtTextColor.Text = "#" + color.ToString().Substring(3);

                SolidColorBrush brush = new SolidColorBrush(color);
                btnTextColor.Background = brush;
            }
        }

        public void GroupRequest()
        {
            DataPacket dataPacket = new DataPacket(0, "");
            var msg =  Newtonsoft.Json.JsonConvert.SerializeObject(dataPacket);
            //string转buffer
            byte[] buffer = Encoding.UTF8.GetBytes(msg);
            tcpClient.sendMessage(buffer);
        }

        public void RegisterRequest(int groupId)
        {
            RegisterRequestData registerRequestData = new RegisterRequestData();
            registerRequestData.GroupId = groupId;
            DataPacket dataPacket = new DataPacket((int)DataPacketType.RegisterRequest, registerRequestData.PacketToJson());
            var msg = Newtonsoft.Json.JsonConvert.SerializeObject(dataPacket);
            //string转buffer
            byte[] buffer = Encoding.UTF8.GetBytes(msg);
            tcpClient.sendMessage(buffer);
        }


        public void LogRequest(int groupId)
        {
            LogRequestData logRequestData = new LogRequestData();
            logRequestData.GroupId = groupId;
            DataPacket dataPacket = new DataPacket((int)DataPacketType.LogRequest, logRequestData.PacketToJson());
            var msg = Newtonsoft.Json.JsonConvert.SerializeObject(dataPacket);
            //string转buffer
            byte[] buffer = Encoding.UTF8.GetBytes(msg);
            tcpClient.sendMessage(buffer);
        }

        //透明度
        public void ApplyOpacityFromTextBox()
        {
            double opacity;
            if (double.TryParse(txtOpacity.Text, out opacity))
            {
                opacity = Math.Max(0, Math.Min(1, opacity));
                txtOpacity.Opacity = opacity;

                Screen screen = new Screen(btnBackgroundColor.Background, btnTextColor.Background);
                screen.UpdateOpacity(opacity);
            }
        }

        private void startHeartTimer()
        {
            heartTimer = new System.Windows.Threading.DispatcherTimer();
            heartTimer.Interval = TimeSpan.FromSeconds(5);
            heartTimer.Tick += HeartTimer_Tick; ;

            // 启动计时器
            heartTimer.Start();
        }

        private void HeartTimer_Tick(object? sender, EventArgs e)
        {
            try
            {
                DateTime dt = getHeartTime();
                // 增加心跳超时判断的容错，避免因系统时间波动导致的误判
                if ((DateTime.Now - dt).TotalSeconds > 20) // 增加容错时间到20秒
                {
                    //服务器掉线
                    if (screen != null)
                    {
                        Logger.Singleton.Warn($"心跳超时: {DateTime.Now - dt}，尝试重连");
                        // 检查是否真的断线（避免多屏环境下的状态混乱）
                        if (tcpClient != null && !tcpClient.ConnectFlag)
                        {
                            SetServerStatus(false);
                            Logger.Singleton.Error("客户端与服务端连接掉线！");
                        }
                    }
                }
                // 心跳发送逻辑优化：降低发送频率，减少网络负载
                if (getServerStatus() && (DateTime.Now - dt).TotalSeconds >= 8) // 改为8秒发送一次
                {
                    try
                    {
                        HeartRequestData heartRequestData = new HeartRequestData();
                        heartRequestData.clientId = ProjectTools.getTcpServer().ClientId;
                        DataPacket dataPacket = new DataPacket((int)DataPacketType.HeartRequest, heartRequestData.PacketToJson());
                        var msg = Newtonsoft.Json.JsonConvert.SerializeObject(dataPacket);
                        byte[] buffer = Encoding.UTF8.GetBytes(msg);
                        tcpClient.sendMessage(buffer);
                        Logger.Singleton.Debug("心跳包已发送");
                    }
                    catch (Exception ex)
                    {
                        Logger.Singleton.Error("发送心跳包失败: " + ex.Message);
                        // 发送失败时不立即断开连接，给系统恢复的机会
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error("心跳计时器处理出错: " + ex.Message);
            }
        }

        private void stopHeartTimer()
        {
            if(heartTimer != null)
            {
                heartTimer.Stop();
                heartTimer.Tick -= HeartTimer_Tick;
                heartTimer = null;
            }
            
        }

        //确认设置
        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            try 
            {
                //socketClientManager.SendMessage();  // 发送分组与是否自动弹出信息
                //socketClientManager.PopupBlackScreen();  //判断是否弹出遮罩层
                //找到选择的分组ID
                if(cmbChooseGroup.SelectedItem == null)
                {
                    System.Windows.MessageBox.Show("请选择分组！", "提示");
                    return;
                }
                string groupName = cmbChooseGroup.SelectedItem.ToString();
                int groupId = -1;

                foreach (var item in groupInfo.GroupInfos)
                {
                    if (item.Name == groupName)
                    {
                        groupId = item.Id;
                    }
                }

                if(groupId != -1)
                {
                    this.groupId = groupId;
                    if (!isRegister)
                    {
                        RegisterRequest(groupId);
                        isRegister = true;
                        this.setHeartTime(DateTime.Now);
                        //heardThread = new Thread(heartThreadFun);
                        //heardThread.IsBackground = true;
                        //heardThread.Start();
                        startHeartTimer();
                    }
                        
                    
                }
               
                System.Windows.MessageBox.Show("已确认修改！", "提示");

                cmbChooseGroup.IsEnabled = false;
                this.btnBlackScreen.IsEnabled = false;
                if (screen != null)
                {
                    screen.Background = btnBackgroundColor.Background;
                    screen.Opacity = double.Parse(txtOpacity.Text);
                    screen.txtBsTime.Foreground = btnTextColor.Background;
                    screen.txtGroupName.Foreground = btnTextColor.Background;
                   // screen.txtInfo.Foreground = btnTextColor.Background;

                }

                //开启监听线程

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("修改分组或自动黑屏错误！", "提示");
            }
            

        }


        private void shutdownHeartThread()
        {
            if (heardThread != null && heardThread.IsAlive)
            {
                heardThread.Interrupt();
            }
        }
        private void SetServerStatus(bool isConnect)
        {
            // 使用更具体的锁对象，避免锁定整个窗口实例
            lock (statusLockObject)
            {
                Logger.Singleton.Info($"开始设置服务器连接状态: {(isConnect ? "已连接" : "断开连接")}");
                
                // 检查是否有状态变化，避免重复操作
                bool currentStatus = getServerStatus();
                if (currentStatus == isConnect)
                {
                    Logger.Singleton.Debug("连接状态未变化，跳过设置");
                    return;
                }
                
                if (isConnect)
                {
                    try
                    {
                        // 确保tcpClient不为空
                        if (tcpClient != null)
                        {
                            // 确保只注册一次事件处理器
                            tcpClient.SocketReceive -= DataReceived;
                            tcpClient.SocketReceive += DataReceived;
                            Logger.Singleton.Debug("已注册SocketReceive事件处理器");
                        }
                        
                        // 更新连接状态标志
                        isServerOk = true;
                        
                        // 确保screen不为空
                        if (screen != null)
                        {
                            // 确保只注册一次日志请求事件
                            screen.LogRequest -= Screen_LogRequest;
                            screen.LogRequest += Screen_LogRequest;
                            Logger.Singleton.Debug("已注册LogRequest事件处理器");
                        }
                        
                        // 更新UI状态
                        if (mcControl != null && mcControl.mcData != null)
                        {
                            mcControl.mcData.ImagePath = @".\Assets\grayCtrl.png";
                        }
                        
                        Logger.Singleton.Info("服务器连接状态设置为：已连接");
                    }
                    catch (Exception ex)
                    {
                        Logger.Singleton.Error("设置连接状态时出错: " + ex.Message, ex);
                        // 发生错误时，确保状态一致
                        isServerOk = false;
                    }
                }
                else
                {
                    try
                    {
                        // 更新连接状态标志
                        isServerOk = false;
                        this.isRegister = false;
                        
                        // 安全地移除事件处理器
                        try
                        {
                            if (tcpClient != null)
                            {
                                tcpClient.SocketReceive -= DataReceived;
                                Logger.Singleton.Debug("已移除SocketReceive事件处理器");
                            }
                            
                            if (screen != null)
                            {
                                screen.LogRequest -= Screen_LogRequest;
                                Logger.Singleton.Debug("已移除LogRequest事件处理器");
                            }
                        }
                        catch (Exception eventEx)
                        {
                            Logger.Singleton.Warn("移除事件处理器时出错: " + eventEx.Message);
                            // 继续执行，不中断流程
                        }
                        
                        // 停止心跳计时器
                        stopHeartTimer();
                        
                        // 断开连接
                        try
                        {
                            disConnect();
                            Logger.Singleton.Debug("已执行断开连接操作");
                        }
                        catch (Exception disconnectEx)
                        {
                            Logger.Singleton.Error("断开连接时出错: " + disconnectEx.Message, disconnectEx);
                            // 继续执行，不中断流程
                        }
                        
                        // 更新UI状态
                        if (mcControl != null && mcControl.mcData != null)
                        {
                            mcControl.mcData.ImagePath = @".\Assets\redCtrl.png";
                        }
                        
                        Logger.Singleton.Info("服务器连接状态设置为：断开连接");
                        
                        // 使用try-catch包裹UI更新，确保即使UI操作失败也不会影响核心逻辑
                        try
                        {
                            System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                            {
                                try
                                {
                                    // 安全地更新UI元素
                                    if (cmbChooseGroup != null)
                                    {
                                        cmbChooseGroup.Items.Clear();
                                        cmbChooseGroup.IsEnabled = true;
                                    }
                                    
                                    if (btnConnect != null)
                                    {
                                        btnConnect.IsEnabled = true;
                                    }
                                    
                                    if (btnBlackScreen != null)
                                    {
                                        btnBlackScreen.IsEnabled = true;
                                    }
                                    
                                    // 确保黑屏窗口不可见
                                    if (screen != null)
                                    {
                                        try
                                        {
                                            screen.Visibility = Visibility.Collapsed;
                                            screen.isBlackScreen = false;
                                        }
                                        catch (Exception screenEx)
                                        {
                                            Logger.Singleton.Error("更新屏幕状态时出错: " + screenEx.Message);
                                        }
                                    }
                                    
                                    // 确保主窗口可见，方便用户重新连接
                                    try
                                    {
                                        this.Visibility = Visibility.Visible;
                                        ProjectTools.ShowWindow(this, Utils.ScreenPosition.Center);
                                    }
                                    catch (Exception windowEx)
                                    {
                                        Logger.Singleton.Error("显示主窗口时出错: " + windowEx.Message);
                                    }
                                }
                                catch (Exception uiEx)
                                {
                                    Logger.Singleton.Error("更新UI状态时出错: " + uiEx.Message, uiEx);
                                }
                            }));
                        }
                        catch (Exception dispatchEx)
                        {
                            Logger.Singleton.Error("调度UI更新时出错: " + dispatchEx.Message, dispatchEx);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Singleton.Error("设置断开状态时出错: " + ex.Message, ex);
                    }
                }
            }
        }

        private bool getServerStatus()
        {
            lock (statusLockObject) // 添加锁以确保线程安全的状态读取
            {
                return isServerOk;
            }
        }


        //连接
        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 禁用按钮，防止重复点击
                btnConnect.IsEnabled = false;
                
                Logger.Singleton.Info("开始连接服务器...");
                
                // 确保在重新连接前先断开旧连接
                if (tcpClient.ConnectFlag)
                {
                    Logger.Singleton.Info("断开现有连接...");
                    disConnect();
                }
                
                // 重新初始化TCP客户端
                bool isConnect = tcpClient.Init();
                
                if(isConnect)
                {
                    SetServerStatus(true);
                    Logger.Singleton.Info("服务器连接成功");
                    System.Windows.MessageBox.Show("已连接服务端！", "提示");
                    GroupRequest();
                }
                else
                {
                    SetServerStatus(false);
                    Logger.Singleton.Error("服务器连接失败");
                    System.Windows.MessageBox.Show("连接服务器失败！", "错误");
                    btnConnect.IsEnabled = true;
                }
            }
            catch (Exception ex)
            {
                SetServerStatus(false);
                Logger.Singleton.Error("连接服务端异常：" + ex.Message, ex);
                System.Windows.MessageBox.Show("连接服务端失败：" + ex.Message, "错误");
                btnConnect.IsEnabled = true;
            }
        }



        private void disConnect()
        {
            tcpClient.Stop();
        }

        private void ShowMainWindow_Click(object sender, RoutedEventArgs e)
        {
            ProjectTools.ShowWindow(this, Utils.ScreenPosition.Center);
            this.Visibility = Visibility.Visible;
        }

        private void PopupBlackScreen_Click(object sender, RoutedEventArgs e)
        {
            ProjectTools.ShowWindow(screen, Utils.ScreenPosition.Center);
            screen.Visibility = Visibility.Visible;

        }

        private void Exist_Click(object sender, RoutedEventArgs e)
        {
            screen.isBlackScreen = false;
            System.Windows.Application.Current.Shutdown();
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Visibility = Visibility.Collapsed;
        }

        private void MyNotifyIcon_TrayMouseDoubleClick(object sender, RoutedEventArgs e)
        {
            ProjectTools.ShowWindow(this, Utils.ScreenPosition.Center);
            this.Visibility = Visibility.Visible;
        }

        private void btnDisconnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (tcpClient.ConnectFlag)
                {
                   
                    //tcpClient.Stop();
                  //  cmbChooseGroup.Items.Clear();

                    //btnConnect.IsEnabled = true;
                    //cmbChooseGroup.IsEnabled = true;
                    //this.btnBlackScreen.IsEnabled = true;
                    //this.isRegister = false;
                    SetServerStatus(false);
               
                    if (screen != null)
                    {
                        screen.isBlackScreen = false;
                        screen.LogRequest -= Screen_LogRequest;
                        screen.Visibility = Visibility.Collapsed;
                        ProjectTools.ShowWindow(this, Utils.ScreenPosition.Center);
                        this.Visibility = Visibility.Visible;
                    }
                    System.Windows.MessageBox.Show("已断开连接！", "提示");
                }
                else
                {
                    System.Windows.MessageBox.Show("未建立连接！", "提示");
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("断开连接出错：" + ex.Message, "提示");
            }
        }
    }
}